package com.hnnu.shoppingtoghter.demo.controller;

import com.github.pagehelper.PageInfo;
import com.hnnu.shoppingtoghter.demo.entity.Project;
import com.hnnu.shoppingtoghter.demo.entity.SysUser;
import com.hnnu.shoppingtoghter.demo.service.ProjectService;
import com.hnnu.shoppingtoghter.demo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpSession;
import java.util.List;

/*** @Description: 登录注册
 * @Author: PDY
 * @CreateTime： 2022/7/3 1:34 
 */
@Controller
@Slf4j
public class LoginController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private ProjectService projectService;

    //首页跳转

    @GetMapping("/index")


    public String inxdex(Project project, Model model){

        model.addAttribute("project", project);
        System.out.println("project =" + project);
        List<Project> projectList = projectService.selectListByProject(project);
        System.out.println("projectList =" + projectList);
        model.addAttribute("projectList", projectList);


        return "index";
    }

    @RequestMapping("/index")
    public String index(HttpSession session) {

        Object userObj = session.getAttribute("user");
        if (null == userObj) {
            //                 return "login";  //转发请求
            return "redirect:/login";//重定向
        }
        return "index";//index 指的是templates 目录下的html文件名
    }

    //实现登录--彭德宇
    @GetMapping("/login")
    public String login() {
        return "/login";
    }

    @PostMapping("/login")
    public String toLogin(HttpSession session,
                          String userCode, String userPassword) {
        System.out.println("userCode =  " + userCode + "userPassword =" + userPassword);
        //验证账号密码是否正确  从数据库中查
        SysUser user = userService.selectUserByUserCodeUserPassword(userCode, userPassword);
        if (null == user) {
            return "login";
        }
        session.setAttribute("user", user);
        return "redirect:/index";//重定向
    }

    //退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 将session 中登录用户信息删除，实现退出功能
        session.removeAttribute("user");
        //将页面重定向到登录页面
        return "redirect:/login";
    }

}
